from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys, os

class ImageView(QGraphicsView):

	def __init__(self, parent=None):
		super(ImageView, self).__init__(parent)

		self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
		self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

		self.scene = QGraphicsScene()
		self.setScene(self.scene)
	
		self.centerOn(1.0,1.0)
		self.currentImageGfxItem = None



	def setImage(self, path):
		if self.currentImageGfxItem: # Make sure we only have 1 item on scene
			self.scene.removeItem(self.currentImageGfxItem)

		currentImage = QPixmap(path)
		self.currentImageGfxItem = self.scene.addPixmap(currentImage)

		self.resizeCurrentImage(self.frameSize())


	def resizeCurrentImage(self, size):
		item =  self.items()[0]

		#pixmap = self.currentImage
		pixmap = self.currentImageGfxItem.pixmap()
		pixmap = pixmap.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation)

		self.centerOn(1.0,1.0)

		item.setPixmap(pixmap)

		centerPosW = (size.width()-pixmap.width())/2
		centerPosH = (size.height()-pixmap.height())/2
		item.setPos(centerPosW,centerPosH)



	def resizeEvent(self, event):
		if not self.currentImageGfxItem:
			return
		self.resizeCurrentImage(event.size())

	
